import Sortable from 'sortablejs'

export function initDrag($this, className) {
  // // 阻止默认行为
  // document.body.ondrop = function (event) {
  //   event.preventDefault();
  //   event.stopPropagation();
  // };
  const wrapperTr = document.querySelector(className||''+' .el-table__header-wrapper tr')
  Sortable.create(wrapperTr, {
    ghostClass: "none",
    animation: 180,
    delay: 0,
    onEnd: evt => {
      if (evt.oldIndex == evt.newIndex) return;
      let columnsOut = [...$this.columnsOut];
      const oldItem = columnsOut[evt.oldIndex]
      columnsOut.splice(evt.oldIndex, 1)
      columnsOut.splice(evt.newIndex, 0, oldItem)

      $this.columnsOut = [];
      $this.$nextTick(function () {

        $this.columnsOut = columnsOut;

      });
      let columns = [...$this.columns];
      for (let index in columns) {
        columns[index].sort = index + columns.length;
      }
      for (let index in columnsOut) {
        for (let object of columns) {
          if (object.name === columnsOut[index].name) {
            object.sort = index;
            break;
          }
        }

      }
      columns.sort((a, b) => a.sort - b.sort);
      for (let index in columns) {
        columns[index].sort = index;
      }
      $this.columns = columns;
    }
  })
}
